const Router = require('koa-router');
const uuid = require('../common/uuid');
let router = new Router();

router.post('*', async (ctx, next) => {
  console.log('aaa');
  let { username, psw } = ctx.request.body;
  if (ctx.request.username && !username && !psw) {
    ctx.session.maxAge = 86400000;
    console.log(`${ctx.request.username}利用session登陆，重置session过期时间`);
    ctx.body = { code: 1, msg: username ? '登陆成功' : ctx.request.username };
  } else {
    try {
      //查看密码用户名是否正确
      let result = await ctx.db.select('user_table', 'username', {
        username,
        psw
      });
      if (result[0]) {
        //登陆成功重置session
        ctx.session.user_symbol = uuid();
        // console.log(ctx.session.user_symbol, 666);
        await ctx.db.update(
          'sess_table',
          { username },
          { user_symbol: ctx.session.user_symbol }
        );

        ctx.body = { code: 1, msg: '登陆成功' };
      } else {
        ctx.body = { code: 0, msg: '登录失败,用户名或密码不正确' };
      }
    } catch (e) {
      ctx.body = { code: 0, msg: '登录失败' };
    }
  }
});
router.get('*', async ctx => {
  ctx.redirect('/');
});
module.exports = router.routes();
